import {
  Dialog
} from 'vant';
import * as services from 'services/wechat';

export default {
  state: {
    location: null,
  },
  getters: {
    location: state => state.location,
  },
  actions: {
    async getWechatSignInfo({
      commit,
      state
    }, payload) {
      const {
        object
      } = await services.getWechatSignInfo(payload);

      wx.config({
        //debug: true,
        appId: object.appid, // 必填，公众号的唯一标识
        timestamp: object.timestamp, // 必填，生成签名的时间戳
        nonceStr: object.noncestr, // 必填，生成签名的随机串
        signature: object.signature, // 必填，签名，见附录1
        jsApiList: [
          'getLocation',
          'openLocation',
          'hideMenuItems',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'scanQRCode',
          'chooseImage',
          'uploadImage'
        ]
      });
      wx.ready(function () {
        wx.getLocation({
          type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function (res) {
            const {
              latitude, // 纬度，浮点数，范围为90 ~ -90
              longitude, // 经度，浮点数，范围为180 ~ -180。
              speed, // 速度，以米/每秒计
              accuracy // 位置精度
            } = res;
            commit('SET_LOCATION', {
              latitude,
              longitude
            });
          }
        });
      });
      wx.error(function (res) {
        Dialog.alert({
          title: '提示',
          message: JSON.stringify(res)
        }).then(() => {
          // on close
        });
        console.log(res);
      });
    },
  },
  mutations: {
    SET_LOCATION(state, payload) {
      // 设置地理位置
      state.location = payload;
    }
  },
};
